package com.pms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;


import com.pms.entity.Project;
import com.pms.entity.User;
import com.pms.entity.UserProject;
import com.pms.util.DBHelp;
import com.pms.util.RowMapper;

public class UserProjectDao {
	private DBHelp<UserProject> db=new DBHelp<UserProject>();
	public void save(UserProject up) {
		String sql="INSERT INTO t_user_project(userid,projectid,role) VALUES(?,?,?)";
		db.executeSQL(sql, up.getUserId(),up.getProjectId(),up.getRole());
	}
	public UserProject findById(String projectId,String userId){
		StringBuilder sql=new StringBuilder();
		sql.append("SELECT tup.userid,tu.username,tu.nickname,tu.password,tu.picture,tup.projectid,tp.projectname,tp.desc,tp.createtime,role FROM t_user_project AS tup ");
		sql.append("LEFT JOIN t_user AS tu ON tup.userid = tu.userid ");
		sql.append("LEFT JOIN t_project AS tp ON tup.projectid = tp.projectid ");
		sql.append("WHERE tup.projectid=? AND tup.userid=?");
		return db.executeQueryForObject(sql.toString(),new UserProjectRowMapper(),projectId,userId);
	}
	public class UserProjectRowMapper implements RowMapper<UserProject>{

		
		public UserProject mapRow(ResultSet rs) throws SQLException {
			UserProject up=new UserProject();
			up.setRole(rs.getString("role"));
			
			User user=new User(); 
			user.setUserId(rs.getString("userId"));
			user.setUserName(rs.getString("userName"));
			user.setPassword(rs.getString("password"));
			user.setNickName(rs.getString("nickName"));
			user.setPicture(rs.getString("picture"));
			
			up.setUser(user);
			up.setUserId(rs.getString("userId"));
			
			
			Project project=new Project();
			project.setProjectId(rs.getString("projectId"));
			project.setProjectName(rs.getString("projectName"));
			project.setDesc(rs.getString("desc"));
			project.setCreateTime(rs.getString("createTime"));
			
			up.setProject(project);
			up.setProjectId(rs.getString("projectId"));
			
			return up;
			
		}
		
		
	}
	

}
